package com.leetcode.no861;

public class Solution {
    public int matrixScore(int[][] A) {
        int len = A.length;

        if (len == 0) {
            return 0;
        }

        // 先把第一列全变成1
        for (int i = 0; i < len; i++) {
            if (A[i][0] != 1) {
                moveRow(A, i);
            }
        }

        // 接下来每一列，如果0的数量超过1，就转换
        for (int j = 1; j < A[0].length; j++) {
            int count = 0;
            for (int i = 0; i < A.length; i++) {
                if (A[i][j] == 0) {
                    count++;
                }
            }
            if (count > A.length / 2) {
                moveCol(A, j);
            }
        }

        int res = 0;

        // 计算结果
        for (int i = 0; i < A.length; i++) {
            int sum = 0;
            for (int j = 0; j < A[0].length; j++) {
                sum = sum * 2 + A[i][j];
            }
            res += sum;
        }
        return res;
    }


    private void moveRow(int[][] A, int n) {
        for (int i = 0; i < A[0].length; i++) {
            A[n][i] ^= 1;
        }
    }

    private void moveCol(int[][] A, int n) {
        for (int i = 0; i < A.length; i++) {
            A[i][n] ^= 1;
        }
    }
}
